<template>
  <ContentWrap>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px"
             label-width="100px" @submit.native.prevent>
      <el-form-item label="归属学校" prop="schoolId" v-if="tenantId == 1">
        <el-select v-model="queryParams.schoolId" placeholder="请选择" class="!w-240px" filterable
                   default-first-option clearable>
          <el-option v-for="item in schools" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="房间号码" prop="number">
        <el-input v-model="queryParams.number" class="!w-240px" clearable maxlength="10"
                  placeholder="请输入房间号" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="专属人手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" class="!w-240px" clearable maxlength="11"
                  placeholder="请输入专属人手机号" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择类型" class="!w-240px" clearable>
          <el-option v-for="item in roomTypes" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择琴房状态" clearable
                   class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YXT_ROOM_STATUS)"
                     :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="对外预约状态" prop="externalSubStatus">
        <el-select v-model="queryParams.externalSubStatus" placeholder="请选择对外预约状态" clearable
                   class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YXT_EXTERNAL_SUB_STATUS)"
                     :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          重置
        </el-button>
        <el-button v-hasPermi="['yxt:room:create']" plain type="primary"
                   @click="openForm('create')">
          新增
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['yxt:room:open']" :disabled="isEmpty(selectKeys)" plain
                   type="primary" @click="onOpen('确认开启所选琴房?', false)">
          开启空间
        </el-button>
        <el-button v-hasPermi="['yxt:room:close']" :disabled="isEmpty(selectKeys)" plain
                   type="danger" @click="onClose">
          关闭空间
        </el-button>
        <el-button v-hasPermi="['yxt:room:lock']" :disabled="isEmpty(selectKeys)" plain
                   type="warning" @click="onLock">
          锁定空间
        </el-button>
        <el-button v-hasPermi="['yxt:room:open']" plain type="success"
                   @click="onOpen('确认开启全部琴房?', true)">
          一键开启
        </el-button>
        <el-button v-hasPermi="['yxt:room:close']" plain type="danger"
                   @click="onClose('确认关闭全部琴房?', true)">
          一键关闭
        </el-button>
        <el-button v-hasPermi="['yxt:room:door:remote']" :disabled="isEmpty(selectKeys)" plain
                   type="primary" @click="onRemote">
          远程开门
        </el-button>
        <el-button v-hasPermi="['yxt:room:door:keep']" :disabled="isEmpty(selectKeys)" plain
                   type="primary" @click="onKeep(true)">
          一键常开门
        </el-button>
        <el-button v-hasPermi="['yxt:room:door:keep']" :disabled="isEmpty(selectKeys)" plain
                   type="primary" @click="onKeep(false)">
          一键常关门
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" @selection-change="selectionChange">
      <el-table-column type="selection" fixed align="center" width="50"/>
      <el-table-column label="房间号" prop="number" min-width="80"/>
      <el-table-column label="类型" prop="typeName" min-width="100"/>
      <el-table-column label="教学楼" prop="buildingName" min-width="120"/>
      <el-table-column label="楼层" prop="floor" min-width="60"/>
      <el-table-column label="对外预约状态" prop="externalSubStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.YXT_EXTERNAL_SUB_STATUS" :value="scope.row.externalSubStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="门禁类型" prop="accessType" min-width="150" show-overflow-tooltip>
        <template #default="scope">
                    <span v-for="item in scope.row.accessType">
                        <dict-tag :type="DICT_TYPE.YXT_ROOM_ACCESS_TYPE" :value="item"/>&nbsp;
                    </span>
        </template>
      </el-table-column>
      <el-table-column label="预约人数" prop="subscribeNum" min-width="60"/>
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.YXT_ROOM_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column :formatter="dateFormatter" align="center" label="创建时间" prop="createTime"
                       width="180"/>
      <el-table-column :width="150" align="center" label="操作" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="() => router.push('detail/'+scope.row.id)">
            查看
          </el-button>
          <el-button v-hasPermi="['yxt:room:update']" link type="primary"
                     @click="openForm('update', scope.row.id)">
            编辑
          </el-button>
          <el-button v-hasPermi="['yxt:room:delete']" link type="danger"
                     @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo"
                :pageSizes="[100,300,500,1000]" :total="total" @pagination="getList"/>
  </ContentWrap>

  <!-- 关闭和锁定原因输入弹框 -->
  <Dialog v-model="dialog.visible" title="" width="360">
    <el-form ref="dialogFormRef" :model="dialog">
      <el-form-item label="操作原因" prop="reason"
                    :rules="[{required: true, message: '请输入原因', trigger: ['blur', 'change']}]">
        <el-input v-model="dialog.reason" placeholder="请输入原因"/>
      </el-form-item>
      <el-form-item v-if="dialog.actionType === 'lock'" label="锁定时间" prop="lockDate"
                    :rules="[{required: true, message: '请选择锁定时间', trigger: ['blur', 'change']}]">
        <el-date-picker v-model="dialog.lockDate" unlink-panels placeholder="请选择时间" type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="handleDialogSubmit">确 定</el-button>
      <el-button @click="handleDialogCancel">取 消</el-button>
    </template>
  </Dialog>

  <ExclusiveRoomForm ref="formRef" @success="getList"/>
</template>

<script lang="ts" setup>
import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import {useRoomApi, useRoomTypeApi} from "@/api/yxt/room";
import ExclusiveRoomForm from "@/views/yxt/room/exclusive/ExclusiveRoomForm.vue";
import {useConfirm, useMessage} from "@/components/Notice";
import {isEmpty} from "lodash-es";
import {FormInstance} from "element-plus";
import router from "@/router";
import {getTenantId} from "@/utils/auth";
import {useSchoolApi} from "@/api/yxt/school";

defineOptions({name: 'YxtExclusiveRoom'})

const tenantId = getTenantId();

const roomApi = useRoomApi();
const schoolApi = useSchoolApi();
const roomTypeApi = useRoomTypeApi();
const {t} = useI18n()

const loading = ref<boolean>(true)
const total = ref<number>(0)
const list = ref<Array<any>>([])
const selectKeys = ref<Array<any>>([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  schoolId: '',
  number: '',
  typeId: undefined,
  status: undefined,
  externalSubStatus: undefined,
  roomType: 1
})
const queryFormRef = ref()
const roomTypes = ref<Array<any>>([])
const schools = ref<Array<any>>([])

// 新增：弹框数据
const dialog = reactive({
  visible: false,
  reason: '系统维护中',
  lockDate: undefined as Date | undefined,
  actionType: '' as 'close' | 'lock' // 记录操作类型
});

const dialogFormRef = ref<FormInstance>();

function handleDialogSubmit() {
  if (dialog.reason.trim() === '') {
    useMessage('请输入原因');
    return;
  }
  if (dialog.actionType === 'lock' && !dialog.lockDate) {
    useMessage('请选择锁定时间');
    return;
  }
  dialog['action']();
  dialog.visible = false;
}

function handleDialogCancel() {
  dialog.lockDate = undefined;
  dialog.visible = false;
  dialog.reason = '系统维护中';
}

const getList = async () => {
  loading.value = true
  try {
    const data = await roomApi.getPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

function selectionChange(list: Array<any>) {
  selectKeys.value = [];
  list.forEach((item) => selectKeys.value.push(item.id));
}

function onOpen(message: string, bol: boolean) {
  useConfirm(message, () => {
    roomApi.open(bol ? [] : selectKeys.value).then(() => {
      getList().finally(() => useMessage("开启成功"));
    });
  })
}

function onClose() {
  dialog.reason = '系统维护中'; // 重置原因
  dialog.lockDate = undefined; // 重置锁定时间
  dialog.actionType = 'close'; // 设置操作类型
  dialog.visible = true; // 显示弹框
  dialogFormRef.value?.resetFields();
  // 保存状态
  dialog['action'] = () => {
    roomApi.close({
        roomIds: selectKeys.value,
        updateReason: dialog.reason
      }
    ).then(() => {
      getList().finally(() => useMessage("关闭成功"));
    });
  }
}

const dateFormRef = ref<FormInstance>();
const lock = ref<any>({
  visible: false
})

function onLock() {
  dialog.reason = '系统维护中'; // 重置原因
  dialog.lockDate = undefined; // 重置锁定时间
  dialog.actionType = 'lock'; // 设置操作类型
  dialog.visible = true; // 显示弹框
  dialogFormRef.value?.resetFields();
  // 保存状态
  dialog['action'] = () => {
    roomApi.lock({
      ids: selectKeys.value,
      date: dialog.lockDate,
      updateReason: dialog.reason // 传递原因
    }).then(() => {
      onCancel();
      getList().finally(() => useMessage("锁定成功"));
    });
  }
}

function onSubmit() {
  dateFormRef.value?.validate((valid) => {
    if (valid) {
      roomApi.lock({
        ids: selectKeys.value,
        date: lock.value.date
      }).then(() => {
        onCancel();
        getList().finally(() => useMessage("锁定成功"));
      });
    }
  })
}

function onCancel() {
  lock.value.visible = false;
  lock.value.date = undefined;
}

function onRemote() {
  useConfirm("确认对所选琴房进行开门操作?", () => {
    roomApi.remote(selectKeys.value).then(() => {
      getList().finally(() => useMessage("请求已发送"));
    });
  })
}

function onKeep(keep: boolean) {
  useConfirm("确认对所选琴房进行一键" + (keep ? "常开" : "常关") + "操作?", () => {
    roomApi.keep({
      ids: selectKeys.value,
      keep: keep
    }).then(() => {
      getList().finally(() => useMessage("请求已发送"));
    });
  })
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = (id: number) => {
  useConfirm("确定要删除琴房吗？删除后关联预约单也会删除哦", async () => {
    await roomApi.deleteExclusive(id);
    getList().finally(() => useMessage(t('common.delSuccess')));
  });
}

onMounted(async () => {
  await getList();
  roomTypes.value = await roomTypeApi.getRoomTypeList();
  schools.value = await schoolApi.getSimpleList();
})
</script>
